import React, { useRef, useState, useEffect } from 'react';
import { Tooltip } from 'tdesign-react';

interface MultiLineTextProps {
  value: any;
  maxLines?: number;
  lineHeight?: number;
  className?: string;
  style?: React.CSSProperties;
}

const MultiLineText: React.FC<MultiLineTextProps> = ({
  value,
  maxLines = 3,
  lineHeight = 20,
  className,
  style
}) => {
  const ref = useRef<HTMLDivElement>(null);
  const [overflow, setOverflow] = useState(false);

  useEffect(() => {
    const el = ref.current;
    if (el) {
      setOverflow(el.scrollHeight > el.clientHeight + 1); // 容差1像素
    }
  }, [value]);

  // 处理各种类型的值
  if (value === null || value === undefined || value === '') {
    return <span className={className} style={style}>{'-'}</span>;
  }

  // 如果是对象，转换为字符串
  if (typeof value === 'object') {
    try {
      value = JSON.stringify(value);
    } catch (e) {
      value = String(value);
    }
  }

  // 确保值是字符串
  const displayValue = String(value);

  const multiLineStyle: React.CSSProperties = {
    display: '-webkit-box',
    WebkitBoxOrient: 'vertical',
    WebkitLineClamp: maxLines,
    textOverflow: 'ellipsis',
    wordBreak: 'break-all',
    whiteSpace: 'normal',
    maxHeight: `${maxLines * lineHeight}px`,
    lineHeight: `${lineHeight}px`,
    overflow: 'hidden',
    ...style
  };

  const content = (
    <div ref={ref} style={multiLineStyle} className={className}>
      {displayValue}
    </div>
  );

  // 如果文本超出，使用Tooltip组件包装
  if (overflow) {
    return (
      <Tooltip
        content={displayValue}
        placement="top"
        showArrow
        trigger="hover"
        destroyOnClose
      >
        {content}
      </Tooltip>
    );
  }

  return content;
};

export default MultiLineText;
